package com.caipiao.lottery.lty.handler.impl;

import com.caipiao.lottery.cache.MemCacheManager;
import com.caipiao.lottery.config.Config;
import com.caipiao.lottery.core.ErrorDef;
import com.caipiao.lottery.data.UserInfo;
import com.caipiao.lottery.dbwarpper.P_API_USER;
import com.caipiao.lottery.log.TraceLogger;
import com.caipiao.lottery.lty.handler.LtyHandler;
import com.caipiao.lottery.lty.handler.LtyHandlerHelper;
import com.caipiao.lottery.lty.message.LtyRequest;
import com.caipiao.lottery.lty.message.LtyResponse;
import com.caipiao.lottery.lty.message.bean.LtyMsgBodyUDM1000;
import jodd.util.StringUtil;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 用户发信息
 */
public class LtyHandlerUDM1000 implements LtyHandler {
    public static void main(String[] args) throws Exception{
        System.out.println((7/2)*6);
        System.out.println("123456789012".substring(0, 20));
    }

    @Override
    public String DoProcess(LtyRequest ltyReq, LtyResponse ltyResp) throws Exception {

        LtyMsgBodyUDM1000.Req reqBody = (LtyMsgBodyUDM1000.Req) ltyReq.bodyMsg;
        LtyMsgBodyUDM1000.Resp respBody = new LtyMsgBodyUDM1000.Resp();
        ltyResp.bodyMsg = respBody;

        //查询信息
        UserInfo userInfo = new UserInfo();
        boolean db_r = P_API_USER.prGetUserInfo(ltyReq.msgId, reqBody.machineCode,
                reqBody.regCode, userInfo);

        if (!db_r) {
            throw new Exception("数据库调用 P_API_USER.prGetUserInfo 失败");
        }
        TraceLogger.Lty.debug(ltyReq.msgId + " 查询{regCode:"+reqBody.regCode+"}成功");

        //注册码错误
        if(1 > userInfo.count){
            respBody.result = "51001";
            respBody.resultDesc = LtyHandlerHelper.GetErrorCodeDesc(ltyReq.cmd, respBody.result);
            return ErrorDef.SYS_SUCESS;
        }

        //注册码过期
        long userExpTime = new SimpleDateFormat("yyyyMMddHHmmss").parse(userInfo.expTime).getTime();
        long sysTime = new Date().getTime();
        if(userExpTime <= sysTime){
            respBody.result = "51002";
            respBody.resultDesc = LtyHandlerHelper.GetErrorCodeDesc(ltyReq.cmd, respBody.result);
            return ErrorDef.SYS_SUCESS;
        }

        String pingtaiUrl = Config.Init.GetPropValue("pingtaiUrl", userInfo.pingtaiType);
        respBody.pingtaiUrl = pingtaiUrl;

        if(!StringUtil.isBlank(reqBody.machineCode) && !StringUtil.isBlank(reqBody.regCode)
            && StringUtil.isBlank(reqBody.url)){
            respBody.result = "60003";
            respBody.resultDesc = LtyHandlerHelper.GetErrorCodeDesc(ltyReq.cmd, respBody.result);
            return ErrorDef.SYS_SUCESS;
        }

        if(!StringUtil.isBlank(reqBody.url) && !StringUtil.isBlank(reqBody.mess)
                && 3 < reqBody.url.length() && 3 < reqBody.mess.length()){
            //判断缓存中用户信息，一段时间内不能重复发送
            String memCa = (String) MemCacheManager.Instance().common_cache.GetCacheData(ltyReq.msgId, userInfo.id);
            if(!StringUtil.isBlank(memCa)){
                respBody.result = "60002";
                respBody.resultDesc = LtyHandlerHelper.GetErrorCodeDesc(ltyReq.cmd, respBody.result);
                return ErrorDef.SYS_SUCESS;
            }

            //判断在线用户数
            int onlineUserCount = Integer.parseInt(Config.Init.GetPropValue("onlineUserCount"));
            Map < String, Integer > result = new HashMap< String, Integer >();
            db_r = P_API_USER.queryOnlineUserCount(ltyReq.msgId, userInfo.id, result) ;
            if (!db_r) {
                throw new Exception("数据库调用 P_API_USER.queryOnlineUserList 失败");
            }
            //判断是否超出
            if(onlineUserCount - 1 < result.get("count")){
                respBody.result = "60001";
                respBody.resultDesc = LtyHandlerHelper.GetErrorCodeDesc(ltyReq.cmd, respBody.result);
                return ErrorDef.SYS_SUCESS;
            }

            List<String> messOne = new ArrayList<String>();
            String[] messArr = reqBody.mess.split("<hah>");
            if(messArr.length > 50){
                for(int mc = 0; mc < 50; mc++){
                    if(StringUtil.isBlank(messArr[mc])){
                        continue;
                    }
                    messOne.add(messArr[mc].replaceAll("\r", ""));
                }
            } else {
                for(String str:messArr){
                    if(StringUtil.isBlank(str)){
                        continue;
                    }
                    messOne.add(str.replaceAll("\r", ""));
                }
            }

            //消息加倍
            List<String> mess = new ArrayList<String>();
            for (int c = 0; c < Integer.parseInt(reqBody.sendTimes); c ++){
                mess.addAll(messOne);
            }

            CookieManager.Instance().sendMess(ltyReq.msgId, userInfo, pingtaiUrl+reqBody.url, mess);

            //修改用户在线状态
            db_r = P_API_USER.updateUserOnlineStatus(ltyReq.msgId, userInfo.id, "1");

            if (!db_r) {
                throw new Exception("数据库调用 P_API_USER.updateUserOnlineStatus 失败");
            }
            TraceLogger.Lty.debug(ltyReq.msgId + " 修改用户["+userInfo.id+"]在线状态成功");

            //加入缓存，控制发送数据频次,xx秒内不能重复发送
            //根据用户cookie数、消息条数，计算缓存事件
            int sendMessSecond = ((mess.size()*(Integer.parseInt(reqBody.sendTimes)))/userInfo.cookieCount)*6;
            MemCacheManager.Instance().common_cache.SetCacheDataWithSec(userInfo.id, userInfo.id, sendMessSecond);
        }

        respBody.result = "0";
        respBody.resultDesc = LtyHandlerHelper.GetErrorCodeDesc(ltyReq.cmd, respBody.result);

        return ErrorDef.SYS_SUCESS;
    }

}
